//
//  XFComposeViewController.m
//  SinaBlog_OC
//
//  Created by macs on 15/11/19.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

#import "XFComposeViewController.h"
#import "XFUser.h"
#import "XFUserAccountModel.h"
#import "XFNetworkTools.h"
#import "SVProgressHUD.h"
#import "XFPictureSelectController.h"

typedef enum {
  XFComposeToolBarTypePicture,
  XFComposeToolBarTypeMention,
  XFComposeToolBarTypeTrend,
  XFComposeToolBarTypeEmoticon,
  XFComposeToolBarTypeAdd
} XFComposeToolBarType;

@interface XFComposeViewController () <UITextViewDelegate>

@property(nonatomic, weak) UITextView *textView;

@property(nonatomic, weak) UIToolbar *toolBar;

@property(nonatomic, weak) UILabel *placeLable;

@property(nonatomic, weak) XFPictureSelectController *psVc;

@end

@implementation XFComposeViewController

- (void)composeToolBarBtnClick:(UIButton *)btn {

  switch (btn.tag) {
  case XFComposeToolBarTypePicture: {
    [self addpictureView];
  } break;

  default:
    break;
  }
}

- (void)addpictureView {

  [self.psVc.view mas_updateConstraints:^(MASConstraintMaker *make) {
    make.height.equalTo(@320);
  }];
  [self.view layoutIfNeeded];
}

- (void)close {
  [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)compoes {
  //发布微博
  // https://api.weibo.com/2/statuses/update.json
  // https://upload.api.weibo.com/2/statuses/upload.json
  NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";

  NSString *access_token = [[[XFUserAccountModel alloc] init] token];
  NSDictionary *parameters = @{
    @"access_token" : access_token,
    @"status" : self.textView.text
  };
  XFNetworkTools *tools = [XFNetworkTools shareNetWorkTools];
  UIImage *iamge = [self.psVc.picArray firstObject];
  if (iamge != nil) {
    urlString = @"https://upload.api.weibo.com/2/statuses/upload.json";

    NSData *data = UIImagePNGRepresentation(iamge);

    [tools uploadImageWithUrlstring:urlString
                         Parameters:parameters
                          ImageData:data
                        AndFinished:^(NSError *error, NSDictionary *dict) {

                          if (error != nil) {
                            NSLog(@"%@", error);
                            [SVProgressHUD showErrorWithStatus:kErrorTip];
                            return;
                          }
                          [SVProgressHUD showSuccessWithStatus:@"发布成功"];

                        }];

    return;
  }

  [tools requestJsonDictWithHttpMothod:HTTPMethodPOST
                             Urlstring:urlString
                            Parameters:parameters
                           AndFinished:^(NSError *error, NSDictionary *dict) {

                             if (error != nil) {
                               NSLog(@"%@", error);
                               [SVProgressHUD showErrorWithStatus:kErrorTip];
                               return;
                             }
                             [SVProgressHUD showSuccessWithStatus:@"发"
                                                                  @"布成功"];
                           }];
}

- (void)viewDidLoad {
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  [self setupUI];
}

- (void)setupUI {
  self.view.backgroundColor =
      [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)
                      green:((float)arc4random_uniform(256) / 255.0)
                       blue:((float)arc4random_uniform(256) / 255.0)
                      alpha:1.0];
  [self setupNav];
  [self setupTextView];
  [self setupToolBar];
  [self prepareKeyboardNotification];
  [self setupPictureSelectorView];
}

- (void)setupPictureSelectorView {

  XFPictureSelectController *psVc = [[XFPictureSelectController alloc] init];
  psVc.view.backgroundColor =
      [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)
                      green:((float)arc4random_uniform(256) / 255.0)
                       blue:((float)arc4random_uniform(256) / 255.0)
                      alpha:1.0];
  [self addChildViewController:psVc];
  self.psVc = psVc;
  [self.view addSubview:psVc.view];

  [psVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.view);
    make.top.equalTo(self.textView.mas_bottom);
    make.height.equalTo(@0);
  }];
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
  self.placeLable.hidden = textView.hasText;
  self.navigationItem.rightBarButtonItem.enabled = textView.hasText;
}

//监听键盘的回退
- (void)prepareKeyboardNotification {
  [[NSNotificationCenter defaultCenter]
      addObserver:self
         selector:@selector(keyBoardChange:)
             name:UIKeyboardWillChangeFrameNotification
           object:nil];
}
//设置工具条跟随键盘
- (void)keyBoardChange:(NSNotification *)notify {

  NSDictionary *dict = notify.userInfo;
  NSValue *value = dict[UIKeyboardFrameEndUserInfoKey];
  //获取到键盘的位置
  CGRect rect = [value CGRectValue];
  NSTimeInterval duration =
      [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

  //获取键盘的 y值
  CGFloat offset = -kScreenH + rect.origin.y;
  [self.toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(@(offset));
  }];
  [UIView animateWithDuration:duration
                   animations:^{

                     [self.view layoutIfNeeded];
                   }];
}

- (void)setupToolBar {

  UIToolbar *toolBar = [[UIToolbar alloc] init];
  [self.view addSubview:toolBar];
  self.toolBar = toolBar;

  //布局 toolbar
  [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {

    make.left.right.bottom.equalTo(self.view);
    make.height.equalTo(@44);
  }];

  NSArray *itemImages = @[
    @{
      @"imageName" : @"compose_toolbar_picture",
      @"XFComposeToolBarType" : @(XFComposeToolBarTypePicture)
    },
    @{
      @"imageName" : @"compose_mentionbutton_background",
      @"XFComposeToolBarType" : @(XFComposeToolBarTypeMention)
    },
    @{
      @"imageName" : @"compose_trendbutton_background",
      @"XFComposeToolBarType" : @(XFComposeToolBarTypeTrend)
    },
    @{
      @"imageName" : @"compose_emoticonbutton_background",
      @"XFComposeToolBarType" : @(XFComposeToolBarTypeEmoticon)
    },
    @{
      @"imageName" : @"compose_addbutton_background",
      @"XFComposeToolBarType" : @(XFComposeToolBarTypeAdd)
    }
  ];
  //创建按钮数组
  NSMutableArray *items = [NSMutableArray array];

  for (int i = 0; i < itemImages.count; ++i) {

    NSDictionary *dict = itemImages[i];

    NSString *imageName = dict[@"imageName"];
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [btn setImage:[UIImage
                      imageNamed:[NSString stringWithFormat:@"%@_highlighted",
                                                            imageName]]
         forState:UIControlStateHighlighted];

    [btn addTarget:self
                  action:@selector(composeToolBarBtnClick:)
        forControlEvents:UIControlEventTouchUpInside];
    btn.tag = [dict[@"XFComposeToolBarType"] intValue];
    [btn sizeToFit];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [items addObject:item];
    //添加弹簧
    UIBarButtonItem *flix = [[UIBarButtonItem alloc]
        initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                             target:nil
                             action:nil];

    [items addObject:flix];
  }

  [items removeLastObject];
  self.toolBar.items = items;
}

//添加文本框
- (void)setupTextView {

  UITextView *textView = [[UITextView alloc] init];

  [self.view addSubview:textView];
  self.textView = textView;
  self.textView.font = [UIFont systemFontOfSize:18];
  self.textView.textColor = [UIColor lightGrayColor];
  //  self.textView.text = @"请输入内容";
  self.textView.delegate = self;
  //设置键盘消失模式
  self.textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
  //弹簧效果开启
  self.textView.alwaysBounceVertical = YES;

  [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {

    make.left.right.top.equalTo(self.view);

    make.height.equalTo(@240);
  }];

  //添加 placelable占位文本
  UILabel *placeLable = [[UILabel alloc] init];
  [self.textView addSubview:placeLable];
  placeLable.text = @"请输入内容";
  placeLable.textColor = [UIColor lightGrayColor];
  placeLable.font = [UIFont systemFontOfSize:18];
  self.placeLable = placeLable;
  [self.placeLable mas_makeConstraints:^(MASConstraintMaker *make) {

    make.left.equalTo(self.textView.mas_left).offset(5);
    make.top.equalTo(self.textView.mas_top).offset(8);
  }];
}

//设置navitem,titleView
- (void)setupNav {
  self.navigationItem.leftBarButtonItem =
      [[UIBarButtonItem alloc] initWithTitle:@"关闭"
                                       style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(close)];
  self.navigationItem.rightBarButtonItem =
      [[UIBarButtonItem alloc] initWithTitle:@"发布"
                                       style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(compoes)];

  UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];

  UILabel *desLable = [[UILabel alloc] initWithTitle:@"发布微博"
                                               Color:[UIColor lightGrayColor]
                                                Font:18
                                              Margin:0];
  [titleView addSubview:desLable];
  XFUser *user = [[XFUser alloc] init];
  UILabel *nameLable = [[UILabel alloc] initWithTitle:user.name
                                                Color:[UIColor darkGrayColor]
                                                 Font:14
                                               Margin:0];
  [titleView addSubview:nameLable];
  self.navigationItem.titleView = titleView;

  [desLable mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(titleView.mas_centerX);
    make.top.equalTo(titleView.mas_top);
  }];

  [nameLable mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerX.equalTo(desLable.mas_centerX);
    make.top.equalTo(desLable.mas_bottom);
  }];
}

@end
